// pages/movies/movies.js
// 获取星星数据
var util = require("../../utils/utils.js");
console.log(util);
// 获取全局APP
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var inTheatersUrl = app.globalData.doubanBase + "/v2/movie/in_theaters" + "?start=0&count=3";
    var comingSoonUrl = app.globalData.doubanBase + "/v2/movie/coming_soon" + "?start=0&count=3";
    var top250Url = app.globalData.doubanBase + "/v2/movie/top250" + "?start=0&count=3";
    this.getMovieListData(inTheatersUrl, "inTheaters", "正在热映");
    this.getMovieListData(comingSoonUrl, "comingSoon", "即将上映");
    this.getMovieListData(top250Url, "top250", "豆瓣Top250");

  },
  onMoreTap: function(event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },
  // 点击跳转电影详情
  onMovieTap: function(event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id=' + movieId,
    })
  },
  // 封装成一个请求函数
  getMovieListData: function(url, setteedKey, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'json'
      },
      success: function(res) {
        that.processDoubanData(res.data, setteedKey, categoryTitle);
      },
      fail: function() {
        console.log("failed");
      }
    })
  },
  onCancelImgTap: function(event) {
    this.setData({
      containerShow: true,
      searchPanelShow: false,
      searchResult: {}
    })
  },
  // 搜索框聚焦事件
  onBindFocus: function(event) {
    //先在data中定义两个变量
    this.setData({
      containerShow: false,
      searchPanelShow: true
    })
  },
  onBindConfirm: function(event) {
    //获取输入的变量值
    var text = event.detail.value;
    var searchUrl = app.globalData.searchDouban + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl, "searchResult", "");
  },
  processDoubanData: function(moviesDouban, setteedKey, categoryTitle) {
    var movies = [];
    var subject = moviesDouban.subjects;
    for (var i = 0; i < subject.length; i++) {
      var title = subject[i].title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        title: title,
        average: subject[i].rating.average,
        coverageUrl: subject[i].images.large,
        movieId: subject[i].id,
        stars: util.convertToStarsArray(subject[i].rating.stars)
      }
      movies.push(temp);
    }
    console.log(movies);
    // js动态属性赋值（难点）
    var readyData = {};
    readyData[setteedKey] = {
      movies: movies,
      categoryTitle: categoryTitle
    };
    console.log(readyData);
    this.setData(readyData);
  }
})